<?php
include_once '../fn.php';
loginCheck();
$flag = 'users';
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <title>Users &laquo; Admin</title>
    <link rel="stylesheet" href="../assets/vendors/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="../assets/vendors/font-awesome/css/font-awesome.css">
    <link rel="stylesheet" href="../assets/vendors/nprogress/nprogress.css">
    <link rel="stylesheet" href="../assets/css/admin.css">
    <script src="../assets/vendors/nprogress/nprogress.js"></script>
</head>

<body>
    <script>
        NProgress.start()
    </script>

    <div class="main">
        <nav class="navbar">
            <button class="btn btn-default navbar-btn fa fa-bars"></button>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="profile.html"><i class="fa fa-user"></i>个人中心</a></li>
                <li><a href="login.php"><i class="fa fa-sign-out"></i>退出</a></li>
            </ul>
        </nav>
        <div class="container-fluid">
            <div class="page-title">
                <h1>用户</h1>
            </div>
            <!-- 有错误信息时展示 -->
            <div class="alert alert-danger" style="display: none">
                <strong id="alert-strong">错误！</strong>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <form id="form">
                        <h2>添加新用户</h2>
                        <input type="hidden" name="id">
                        <div class="form-group">
                            <label for="email">邮箱</label>
                            <input id="email" class="form-control" name="email" type="email" placeholder="邮箱">
                        </div>
                        <div class="form-group">
                            <label for="slug">别名</label>
                            <input id="slug" class="form-control" name="slug" type="text" placeholder="slug">
                            <p class="help-block">https://zce.me/author/<strong id="slug-strong">slug</strong></p>
                        </div>
                        <div class="form-group">
                            <label for="nickname">昵称</label>
                            <input id="nickname" class="form-control" name="nickname" type="text" placeholder="昵称">
                        </div>
                        <div class="form-group">
                            <label for="password">密码</label>
                            <input id="password" class="form-control" name="password" type="text" placeholder="密码">
                        </div>
                        <div class="form-group">
                            <input class="btn btn-primary" type="button" value="添加" id="addUser">
                            <input class="btn btn-primary" type="button" value="修改" id="editUser" style="display: none">
                            <input class="btn btn-primary" type="button" value="放弃" id="cancel" style="display: none">
                        </div>
                    </form>
                </div>
                <div class="col-md-8">
                    <div class="page-action">
                        <!-- show when multiple checked -->
                        <a class="btn btn-danger btn-sm" href="javascript:;" style="display: none" id="delMany">批量删除</a>
                    </div>
                    <table class="table table-striped table-bordered table-hover">
                        <thead>
                            <tr>
                                <th class="text-center" width="40"><input type="checkbox" class="selectAll"></th>
                                <th class="text-center" width="80">头像</th>
                                <th>邮箱</th>
                                <th>别名</th>
                                <th>昵称</th>
                                <th>状态</th>
                                <th class="text-center" width="100">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 模板引擎填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入公共侧边栏 -->
    <?php include './inc/aside.php'; ?>

    <script src="../assets/vendors/jquery/jquery.js"></script>
    <script src="../assets/vendors/bootstrap/js/bootstrap.js"></script>
    <script>
        NProgress.done()
    </script>
    <!-- 导入模板引擎 -->
    <script src="../assets/vendors/template/template-web.js"></script>

    <!-- 模板 -->
    <script type="text/html" id="tmp">

    {{ each list v i }}
    <tr>
        <td class="text-center"><input type="checkbox" class="selectThis"></td>
        <td class="text-center"><img class="avatar" src="../{{ v.avatar }}"></td>
        <td>{{ v.email }}</td>
        <td>{{ v.slug }}</td>
        <td>{{ v.nickname }}</td>
        <td>{{ status[v.status] }}</td>
        <td class="text-center" data-id="{{ v.id }}">
            <a href="javascript:;" class="btn btn-default btn-xs" id="editBtn">编辑</a>
            {{ if v.id!=currentId }}
            <a href="javascript:;" class="btn btn-danger btn-xs" id="delBtn">删除</a>
            {{ /if }}
        </td>
    </tr>
    {{ /each }}

    </script>

    <script>
        // 封装一个函数，用于渲染用户数据
        function render() {
            // 与后台进行通信
            $.ajax({
                url: './users/usersGet.php',
                dataType: 'json',
                success: function(info) {
                    console.log(info);

                    // 数据获取成功后使用模板引擎渲染
                    $('tbody').html(template('tmp', {
                        list: info,
                        status: {
                            unactivated: '未激活',
                            activated: '激活',
                            forbidden: '禁止',
                            trashed: '回收站'
                        },
                        currentId: $('.aside').attr('data-userid') 
                    }));
                }
            })
        }

        render();

        // --------------------------------------------------------
        // 删除功能的实现
        $('tbody').on('click', '#delBtn', function() {
            console.log('删除按钮被点了');

            // 与后台进行通信
            $.ajax({
                type: 'get',
                url: './users/usersDel.php',
                data: {
                    id: $(this).parent().attr('data-id')
                },
                dataType: 'json',
                success: function(info) {
                    console.log(info);

                    // 删除完后重新渲染用户列表
                    render();
                }
            });
        });

        // --------------------------------------------------------
        // 全选功能的实现
        $('.selectAll').on('change', function() {
            $('.selectThis').prop('checked', $(this).prop('checked'));

            // 判断显示批量删除
            if ($(this).prop('checked')) {
                $('#delMany').show();
            } else {
                $('#delMany').hide();
            }
        });

        // 单选功能的实现
        $('tbody').on('change', '.selectThis', function() {
            if ($('tbody .selectThis:checked').length == $('tbody .selectThis').length) {
                $('.selectAll').prop('checked', true);
            } else {
                $('.selectAll').prop('checked', false);
            }

            // 判断显示批量删除
            if ($('tbody .selectThis:checked').length != 0) {
                $('#delMany').show();
            } else {
                $('#delMany').hide();
            }
        });

        // -------------------------------------------------------
        // 批量删除功能实现
        $('#delMany').click(function() {
            console.log('批量删除按钮被点了');

            // 构造批量删除的ids
            var ids = '';
            $('tbody .selectThis:checked').each(function(index, domEle) {
                ids += $(domEle).parent().siblings('td[data-id]').attr('data-id') + ',';
            })

            ids = ids.substr(0, ids.length - 1);

            console.log(ids);

            // 与后台进行通信删除
            $.ajax({
                type: 'get',
                url: './users/usersDel.php',
                data: {
                    id: ids
                },
                dataType: 'json',
                success: function(info) {
                    console.log(info);

                    // 删除完重新渲染用户列表页
                    render();
                }
            });

        });

        // -------------------------------------------------------------
        // 别名同步实现
        $('#slug').on('input', function() {
            $('#slug-strong').text($(this).val());
        });

        // -------------------------------------------------------------
        // 添加用户功能实现
        $('#addUser').click(function() {
            var info = $('#form').serialize();
            console.log(info);

            // 与后台通信
            $.ajax({
                type: 'post',
                url: './users/usersAdd.php',
                data: info,
                dataType: 'json',
                beforeSend: function() {
                    // 与后台通信前，判断用户输入是否合法
                    if ($('#email').val().trim().length == 0) {

                        $('#alert-strong').text('输入内容不能为空');
                        $('#alert-strong').parent().show();
                        return false;
                    }else{
                        $('#alert-strong').parent().hide();
                    }
                },
                success: function(info) {
                    console.log(info);
                    
                    // 重新渲染
                    render();

                    // 表单清空
                    $('#form')[0].reset();
                    // 别名同步
                    $('#slug-strong').text('slug');
                }
            })
        });

        // ------------------------------------------------------------
        // 编辑按钮点击功能实现
        $('tbody').on('click','#editBtn',function () {
            console.log('编辑按钮被点了');

            // 将用户id转移给form的隐藏域，基于form来修改
            $('input[type="hidden"]').val($(this).parent().attr('data-id'));

            // 与后台通信，获取id对应的用户信息
            $.ajax({
                type: 'get',
                url: './users/usersGetById.php',
                data: {
                    id: $('input[type="hidden"]').val()
                },
                dataType: 'json',
                success: function (info) {
                    console.log(info);
                    var data = info[0];
                    // 将信息填充到form中
                    $('#email').val(data.email);
                    $('#slug').val(data.slug);
                    // 别名同步
                    $('#slug-strong').text($('#slug').val());
                    $('#nickname').val(data.nickname);
                    $('#password').val(data.password);

                    // 切换按钮
                    $('#addUser').hide();
                    $('#editUser').show();
                    $('#cancel').show();
                }
            });
        });

        // --------------------------------------------------------------
        // 修改按钮点击功能实现
        $('#editUser').click(function () {
            var info = $('#form').serialize();

            console.log(info);
            
            // 与后台通信
            $.ajax({
                type: 'post',
                url: './users/usersUpdate.php',
                data: info,
                dataType: 'json',
                success: function (info) {
                    console.log(info);

                    // 修改完成后重新渲染列表页
                    render();
                    
                    // 将表单清空且按钮切换
                    $('#form')[0].reset();

                    // 别名同步下
                    $('#slug-strong').text('slug');

                    // 切换按钮
                    $('#addUser').show();
                    $('#editUser').hide();
                    $('#cancel').hide();
                }
            });
        });
    </script>
</body>

</html>